package Phaser_7;
import java.util.concurrent.Phaser;
public class 分层处理_多级任务协调 {
    public static void main(String[] args) {
        final int GROUP_COUNT = 3;
        final int TASKS_PER_GROUP = 4;
        final Phaser rootPhaser = new Phaser(GROUP_COUNT);

        for (int g = 0; g < GROUP_COUNT; g++) {
            final int groupId = g;
            final Phaser groupPhaser = new Phaser(1); // 每个组有自己的Phaser
            new Thread(new Runnable() {
                public void run() {
                    // 组内任务
                    for (int t = 0; t < TASKS_PER_GROUP; t++) {
                        final int taskId = t;
                        groupPhaser.register();//共加4，且一定先于groupPhaser.arriveAndAwaitAdvance();执行
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    System.out.println("组" + groupId + "-任务" + taskId + " 开始");
                                    Thread.sleep((long)(Math.random() * 500));
                                    System.out.println("组" + groupId + "-任务" + taskId + " 完成");
                                    groupPhaser.arriveAndDeregister();//共减4
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }

                    // 等待组内所有任务完成
                    groupPhaser.arriveAndAwaitAdvance();//-1
                    System.out.println("组" + groupId + " 全部任务完成");

                    // 通知根Phaser
                    rootPhaser.arriveAndDeregister();
                }
            }).start();
        }

        rootPhaser.arriveAndAwaitAdvance();
        System.out.println("所有组任务已完成");
    }
}
